﻿using System.Data.SqlClient;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.IO;
using System.Data;

namespace 餐饮管理系统
{
    public partial class MainWindow : Window
    {
        private bool is_discount_loaded = false;
        private Button[] mealStarButtons = new Button[5];
        private void InitializeMealStarButtons()
        {
            MealScoreBar.ApplyTemplate();
            for (int i = 0; i < 5; i++)
            {
                string name = "s" + (i + 1);
                mealStarButtons[i] = MealScoreBar.Template.FindName(name, MealScoreBar) as Button;
            }
        }
        public void setMealGrade(int grade)
        {
            if (grade < 0 || grade > 5)
            {
                return;
            }

            for (int i = 0; i < 5; i++)
            {
                //if (i < grade)
                //{ mealStarButtons[i].Visibility = Visibility.Visible; }
                //else
                //{ mealStarButtons[i].Visibility = Visibility.Hidden; }
                mealStarButtons[i].Visibility = i < grade ? Visibility.Visible : Visibility.Hidden;
            }

        }

        private int getMealGrade()
        {
            int grade = 0;
            for (int i = 0; i < 5; i++)
            {
                if (mealStarButtons[i].Visibility == Visibility.Visible)
                {
                    grade++;
                }
            }
            return grade;
        }
        public void loadmealselected() 
        {
            if (this.YouhuiListBox.Items.Count == 0) return;
            if (!is_discount_loaded) return;
            ListBoxItem meal = YouhuiListBox.SelectedItem as ListBoxItem;
            string mealname = meal.Content.ToString().Trim();
            string sqlMeal = "select * from MealTable where name = '" + mealname+"'";
            SqlDataReader dataReaderMeal = databaseConnect.GetDataReader(sqlMeal);
            while (dataReaderMeal.Read())
            {
                this.dishName.Text = dataReaderMeal[1].ToString().Trim();
                this.Price.Text = dataReaderMeal[2].ToString().Trim();
                this.DisCountTextBox.Text = dataReaderMeal[3].ToString().Trim();
                this.Yuanliao_InformationTextBox.Text = dataReaderMeal[4].ToString().Trim();
                this.pricenow.Text = ((double)dataReaderMeal[2] * (double)dataReaderMeal[3]/100).ToString();
                int grade = (int)dataReaderMeal[5];
                setMealGrade(grade);

                if (dataReaderMeal[6] != null && !dataReaderMeal[6].ToString().Equals(""))
                {
                    MealPhoto.Source = DatabaseConnect.ByteArrayToBitmapImage(dataReaderMeal[6] as Byte[]);
                    MealAddPhotoButton.Opacity = 0;
                }
                else
                {
                    MealPhoto.Source = null;
                    MealAddPhotoButton.Opacity = 0.5;
                }
            }

            dataReaderMeal.Close();
        }
        
        public void loadmeals() 
        {
            string sqlList = "select * from MealTable";
            SqlDataReader dataReaderList = databaseConnect.GetDataReader(sqlList);
            ListBoxItem item = new ListBoxItem();
            while (dataReaderList.Read())
            {
                item = new ListBoxItem();
                item.SetResourceReference(ListBoxItem.StyleProperty, "ListBoxItemStyle1");
                item.ApplyTemplate();
                item.Content = dataReaderList[1].ToString().Trim();
                YouhuiListBox.Items.Add(item);
            }
            dataReaderList.Close();
            YouhuiListBox.SelectedIndex = 0;
        }
        
        private void YouhuiListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            // 在此处添加事件处理程序实现。
            if (this.YouhuiListBox.SelectedIndex < 0)
                this.YouhuiListBox.SelectedIndex = 0;
            loadmealselected();
        }

        private void Youhui_addButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // 在此处添加事件处理程序实现。
            ListBoxItem item = new ListBoxItem();
            item.SetResourceReference(ListBoxItem.StyleProperty, "ListBoxItemStyle1");
            item.ApplyTemplate();
            item.Content = "新增菜肴";
            YouhuiListBox.Items.Add(item);
            YouhuiListBox.SelectedItem = item;
            this.Yuanliao_InformationTextBox.Text = "";
            this.Price.Text = 0+"";
            this.DisCountTextBox.Text = 100+ "";
            //string sql1 = "SET IDENTITY_INSERT MealTable ON";
            //this.databaseConnect.ExecuteQuery(sql1);
            //string sql = "insert into MealTable "
            //            + "values("
            //            + "null, '" + dishname + "' , "+price+ " , " + discount + " , '" + ingredients+" ' "
            //            + ")";
            string sql = "insert into MealTable(name) values( '新增菜肴' )";
            this.databaseConnect.ExecuteQuery(sql);
            
            loadmealselected();
        }

        private void Youhui_saveButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // 在此处添加事件处理程序实现。
            string orginname = ((ListBoxItem)this.YouhuiListBox.SelectedItem).Content.ToString();
            string name = this.dishName.Text;
            string ingredients = this.Yuanliao_InformationTextBox.Text;
            string price = this.Price.Text;
            string discount = this.DisCountTextBox.Text;
            int id = this.YouhuiListBox.SelectedIndex+1;
            for (int i = 0; i < this.YouhuiListBox.Items.Count; i++)
                if (((ListBoxItem)YouhuiListBox.Items.GetItemAt(i)).Content.ToString() == name)
                    if (id != i + 1)
                    {
                   
                        MessageBox.Show("已有该菜名，请重新输入");
                        return;
                    }
            float fprice = checkinput(price);
            float fdiscount = checkinput(discount);
            if (fprice < 0)
            {
                MessageBox.Show("价格不得小于0！");
                return;
            }
            if ((fdiscount > 100) || (fdiscount < 0)) {
                MessageBox.Show("折扣必须在0到100之间！");
                return; 
            }

            string sql = "update MealTable "
                      + "set    price =  " + price
                      + "       ,discount = " + discount
                      + "        ,ingredients = '" + ingredients
                      + "'      ,name = '" + name + "'"
                      + "       ,score =" + getMealGrade()
                      + "        where name = '" + orginname + "'";
            this.databaseConnect.ExecuteQuery(sql);

            try
            {
                if (MealPhoto.Source != null)
                {
                    FileStream fs = new FileStream(MealPhoto.Source.ToString().Substring(8), FileMode.Open, FileAccess.Read);
                    Byte[] imageByte = new Byte[fs.Length];
                    fs.Read(imageByte, 0, Convert.ToInt32(fs.Length));
                    fs.Close();
                    sql = "update MealTable set photo = @imgfile where id = " + id;
                    SqlParameter par = new SqlParameter("@imgfile", SqlDbType.Image);
                    par.Value = imageByte;
                    databaseConnect.ExecuteQuery(sql, par);
                }
            }
            catch (Exception)
            { }

            ((ListBoxItem)this.YouhuiListBox.SelectedItem).Content = name;
            this.loadmealselected();
        }

        private void initMealTable()
        {
            YouhuiListBox.Items.Clear();
            loadmeals();
            is_discount_loaded = true;
            loadmealselected();
        }

        public float checkinput(string input ) 
        {
            float temp;
            try
            {
                temp = float.Parse(input);
            }
            catch (Exception) {
                return -1;
            }
            return temp;
        
        }


        private void MealAddPhotoButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Button addButton = sender as Button;
            addButton.ApplyTemplate();
            Image mealPhoto = addButton.Template.FindName("image", addButton) as Image;

            //创建＂打开文件＂对话框
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            //设置文件类型过滤
            dlg.Filter = "图片|*.jpg;*.png;*.gif;*.bmp;*.jpeg";

            // 调用ShowDialog方法显示＂打开文件＂对话框
            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                //获取所选文件名并在FileNameTextBox中显示完整路径
                string filename = dlg.FileName;

                //在image1中预览所选图片
                BitmapImage image = new BitmapImage(new Uri(filename));
                MealPhoto.Source = image;
                MealAddPhotoButton.Opacity = 0;
            }
        }

        private void Youhui_deleteButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // 在此处添加事件处理程序实现。
            //MessageBox.Show("delete");
            string name = this.dishName.Text;

            try
            {
                string sql = "delete from MealTable  where name = '" + name + "'";
                this.databaseConnect.ExecuteQuery(sql);
            }
            catch (Exception)
            {
                MessageBox.Show("订单中已有相关菜目，不能删除！");
                return;
            }
            for (int i = 0; i < 1000; i++) {
                if (name.Equals(this.meal[i]))
                {
                    this.meal[i] = "";
                    break;
                }
            }
                //this.YouhuiListBox.SelectedIndex = 0;
                this.YouhuiListBox.Items.Remove(this.YouhuiListBox.SelectedItem);
            //this.loadmealselected();
        }
    }
}